package com.misboot.document.service.impl;

import cn.ewsd.common.bean.LoginInfo;
import cn.ewsd.common.utils.JsonUtils;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.misboot.document.client.MessageClient;
import com.misboot.document.client.MdataClient;
import com.misboot.document.config.ReqKeys;
import com.misboot.document.controller.MinioController;
import com.misboot.document.dto.*;
import com.misboot.document.exception.SystemException;
import com.misboot.document.model.*;
import com.misboot.document.propertie.ConvertProperties;
import com.misboot.document.propertie.ServerProperties;
import com.misboot.document.service.DfsFileService;
import com.misboot.document.service.FileService;
import com.misboot.document.utils.wps.*;
import com.misboot.document.utils.wps.file.FileUtil;
import com.misboot.document.utils.wps.upload.UploadFileLocation;
import org.apache.http.HttpHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RefreshScope
@Service("FileServiceImpl")
public class FileServiceImpl implements FileService {

    static Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    @Autowired
    private ServerProperties serverProperties;

    @Value("${wps.appid}")
    private String wpsAppid;

    @Value("${wps.domain}")
    private String wpsDomain;

    @Value("${wps.appsecret}")
    private String wpsAppsecret;


    @Value("${redirect.key}")
    private String redirectKey;


    @Value("${redirect.value}")
    private String redirectValue;


    @Autowired
    private MinioController minioController;

    @Autowired
    private DfsFileService dfsFileService;


    /**
     * 获取预览用URL
     *
     * @param fileId     文件id
     * @param userId     用户id
     * @param checkToken 是否校验token
     */

    public Token getViewUrl(String fileId, String userId, boolean checkToken, String bucket) {

        if (!bucket.contains("copy")){
            Example example = new Example(DfsFile.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("puuid", fileId);
            List<DfsFile> dfsFile = dfsFileService.selectByExample(example);
            if (dfsFile.size() == 1){
                String url = dfsFile.get(0).getUrl();
                String name = dfsFile.get(0).getFileName();
                Object bucketAndFileName = minioController.getBucketAndFileName(url);
//            String bucket = ((HashMap) bucketAndFileName).get("bucket").toString();
                String fileNameContainFolder = ((HashMap) bucketAndFileName).get("fileName").toString();
                if (true) {
                    Token t = new Token();
                    String fileName = name;
                    String fileType = FileUtil.getFileTypeByName(fileName);
                    Map<String, String> values = new HashMap<String, String>() {
                        {
                            put(ReqKeys.APP_ID_KEY, wpsAppid);
                            if (checkToken) {
                                put(ReqKeys.TOKEN_TYPE_KEY, "1");
                            }
                            put(ReqKeys.FILE_PATH_KEY, url);
                            put(ReqKeys.USER_ID_KEY, LoginInfo.getUserNameId());
                            put("_w_userName", LoginInfo.getUserName());
                            put(ReqKeys.FILE_TYPE_KEY, "web");
                            put("_w_fileId", fileId);
                            put("_w_uploadType", "minio");
                            put("_w_bucket", bucket);
                            put("_w_fileName", fileNameContainFolder);
                        }
                    };
                    String wpsUrl = null;
                    try {
                        wpsUrl = WpsUtil.getWpsUrl(values, fileType, fileId, wpsAppsecret, wpsDomain);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    t.setToken(fileId);
                    t.setExpires_in(600);
                    t.setWpsUrl(wpsUrl);
                    return t;
                }
            }
        }else {
            String url = dfsFileService.selectCopyFileUrlByBusinessUuid(fileId);
            Object bucketAndFileName = minioController.getBucketAndFileName(url);
            String fileNameContainFolder = ((HashMap) bucketAndFileName).get("fileName").toString();
            if (BeanUtil.isNotEmpty(url)){
                Token t = new Token();
                String fileName = fileNameContainFolder;
                String fileType = FileUtil.getFileTypeByName(fileName);
                Map<String, String> values = new HashMap<String, String>() {
                    {
                        put(ReqKeys.APP_ID_KEY, wpsAppid);
                        if (checkToken) {
                            put(ReqKeys.TOKEN_TYPE_KEY, "1");
                        }
                        put(ReqKeys.FILE_PATH_KEY, url);
                        put(ReqKeys.USER_ID_KEY, LoginInfo.getUserNameId());
                        put("_w_userName", LoginInfo.getUserName());
                        put(ReqKeys.FILE_TYPE_KEY, "web");
                        put("_w_fileId", fileId);
                        put("_w_uploadType", "minio");
                        put("_w_bucket", bucket);
                        put("_w_fileName", fileNameContainFolder);
                    }
                };
                String wpsUrl = null;
                try {
                    wpsUrl = WpsUtil.getWpsUrl(values, fileType, fileId, wpsAppsecret, wpsDomain);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                t.setToken(fileId);
                t.setExpires_in(600);
                t.setWpsUrl(wpsUrl);
                return t;
            }
        }

        return null;
    }


    /**
     * 获取预览用URL
     *
     * @param fileUrl    文件url
     * @param checkToken 是否校验token
     */
    @Override
    public Token getViewUrl(String fileUrl, boolean checkToken, String uuids, String uploadType, String permission) {
        Token t = new Token();

        String fileType = FileUtil.getFileTypeByPath(fileUrl);
        // fileId使用uuid保证出现同样的文件而是最新文件
        UUID randomUUID = UUID.randomUUID();
        String uuid = randomUUID.toString().replace("-", "");
        String userId = LoginInfo.getUserNameId();//工号
        String userName = LoginInfo.getUserName();//姓名
        String avatar_url = "http://vue.misboot.com:9000/oauth-logo/20230227144132-logo.png";//头像

        Map<String, String> values = new HashMap<String, String>() {
            {
                put("_w_appid", wpsAppid);
                if (checkToken) {
                    put("_w_tokentype", "1");
                }
                //put(redirectKey, null);
                put("_w_userid", userId);
                put("_w_username", userName);
                put("_w_avatar_url", avatar_url);
                put("_w_filepath", fileUrl);
                put("_w_filetype", "web");
                put("_w_fileId", uuid);
                put("_w_uploadType", uploadType);
                put("_w_fname", fileUrl.split("/")[3]);
                if (!StringUtils.isEmpty(permission)) {
                    if ("编辑".equals(permission)) {
                        put("_w_permission", "write");
                    } else {
                        put("_w_permission", "read");
                    }
                } else {
                    put("_w_permission", "read");
                }
            }
        };

        String wpsUrl = null;
        try {
            wpsUrl = WpsUtil.getWpsUrl(values, fileType, uuid, wpsAppsecret, wpsDomain);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        t.setToken(uuid);
        t.setExpires_in(600);
        t.setWpsUrl(wpsUrl);

        return t;
    }


    /**
     * 获取预览用URL
     *
     * @param filePath 文件路径
     * @param userId   用户id
     * @param type     请求预览文件类型
     */
    @Override
    public Map<String, Object> getFileInfo(String userId, String filePath, String type, String _w_fileId, Map<String, Object> params) {
        if ("web".equalsIgnoreCase(type)) {
            return getWebFileInfo(filePath, _w_fileId, params);
        }
        return null;
    }


    /**
     * 获取文件元数据
     *
     * @param filePath 文件路径
     */
    private Map<String, Object> getWebFileInfo(String filePath, String _w_fileId, Map<String, Object> params) {
        logger.info("_w_filepath:{}", filePath);

        // 构建默认user信息
        UserDTO wpsUser = new UserDTO(
                Convert.toStr(params.get("_w_userid")),
                Convert.toStr(params.get("_w_username")),
                "write",
                Convert.toStr(params.get("_w_avatar_url"))
        );

        int fileSize = FileUtil.getFileSize(filePath);

        // 构建文件
        FileDTO file = new FileDTO(
                _w_fileId,
                FileUtil.getFileName(filePath),
                1,
                fileSize,
                params.get("_w_userid").toString(),
                new Date().getTime(),
                params.get("_w_userid").toString() + "1",
                new Date().getTime() + 60,
                filePath,
                // 默认设置为无水印，只读权限
                new UserAclBO(),
                new WatermarkBO()
        );
        Map<String, Object> map = new HashMap<>();
        map.put("file", file);
        map.put("user", wpsUser);
        return map;
    }

    /**
     * 获取文件元数据
     *
     * @param userId 用户id
     */
    private Map<String, Object> getDbFileInfo(String userId) {
        //String fileId = Context.getFileId();
        String fileId = "1";

        // 获取文件信息
        //FileEntity fileEntity = this.findOne(fileId);
        FileEntity fileEntity = new FileEntity();
        fileEntity.setId("1");
        fileEntity.setName("log.doc");
        fileEntity.setVersion(1);
        fileEntity.setSize(25);

        // 初始化文件读写权限为read
        String permission;

        // 增加用户权限
        //UserAclEntity userAclEntity = userAclService.getRepository().findFirstByFileIdAndUserId(fileId, userId);
        UserAclEntity userAclEntity = new UserAclEntity();
        userAclEntity.setId(1L);
        userAclEntity.setUserId("1");
        userAclEntity.setFileId("1");
        userAclEntity.setPermission("write");
        userAclEntity.setRename(0);
        userAclEntity.setHistory(0);
        UserAclBO userAcl = new UserAclBO();
        if (userAclEntity != null) {
            BeanUtils.copyProperties(userAclEntity, userAcl);
            permission = userAclEntity.getPermission();
        } else {
            userAcl.setHistory(1);
            userAcl.setRename(1);
            permission = "write";
        }

        // 增加水印
        //WatermarkEntity watermarkEntity = watermarkService.getRepository().findFirstByFileId(fileId);
        WatermarkEntity watermarkEntity = new WatermarkEntity();
        watermarkEntity.setId(1L);
        watermarkEntity.setFileId("1");
        watermarkEntity.setType(0);
        watermarkEntity.setValue(null);
        watermarkEntity.setFillstyle("rgba( 192, 192, 192, 0.6 )");
        watermarkEntity.setFont("bold 20px Serif");
        watermarkEntity.setRotate(BigDecimal.valueOf(0));
        watermarkEntity.setHorizontal(50);
        watermarkEntity.setVertical(50);
        WatermarkBO watermark = new WatermarkBO();
        if (watermarkEntity != null) {
            BeanUtils.copyProperties(watermarkEntity, watermark);
        }

        //获取user
        //UserEntity wpsUser = userService.findOne(userId);
        UserEntity wpsUser = new UserEntity();
        wpsUser.setName("1");
        wpsUser.setId("1");
        wpsUser.setAvatar_url("");
        UserDTO user = new UserDTO();
        if (wpsUser != null) {
            BeanUtils.copyProperties(wpsUser, user);
            user.setPermission(permission);
        }

        // 构建fileInfo
        FileDTO file = new FileDTO();
        BeanUtils.copyProperties(fileEntity, file);
        file.setUser_acl(userAcl);
        file.setWatermark(watermark);

        return new HashMap<String, Object>() {
            {
                put("file", file);
                put("user", user);
            }
        };
    }


    @Override
    public Object createTemplateFile(String template, String puuid, String bucket) {
        boolean typeTrue = FileUtil.checkCode(template);
        if (typeTrue) {
            try {
                return WpsUtil.getTemplateWpsUrl(template, LoginInfo.getUserNameId(), puuid, bucket);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    @Autowired
    private ConvertProperties convertProperties;

    /**
     * 文件原格式	转换后格式
     * word			pdf、png
     * excel		pdf、png
     * ppt			pdf
     * pdf			word、ppt、excel
     *
     * @param srcUri     文件url
     * @param exportType 输出类型
     */
    @Override
    public void convertFile(String taskId, String srcUri, String exportType) {
        if (StringUtils.isEmpty(taskId)) {
            taskId = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        }
        System.out.println("--convertFile:taskId:-> " + taskId);
        String headerDate = Common.getGMTDate();
        Map<String, Object> param = new LinkedHashMap<>();
        param.put("SrcUri", srcUri);
        param.put("FileName", FileUtil.getFileName(srcUri));
        param.put("ExportType", exportType);
        Integer port = null;
        if (serverProperties.getPort() != 443 && serverProperties.getPort() != 80) {
            port = serverProperties.getPort();
        }
//        param.put("CallBack", serverProperties.getDomain() + (port == null ? "" : (":" + port)) + "/v1/3rd/file/convertCallback");//回调地址，文件转换后的通知地址，需保证可访问
        param.put("CallBack", "https://b399u28635.zicp.fun/document" + "/v1/3rd/file/convertCallback");
        param.put("TaskId", taskId);
        //Content-MD5 表示请求内容数据的MD5值，对消息内容（不包括头部）计算MD5值获得128比特位数字，对该数字进行base64编码而得到，如”eB5eJF1ptWaXm4bijSPyxw==”，也可以为空；
        String contentMd5 = Common.getMD5(param);
        //签名url的参数不带请求参数
        String authorization = SignatureUtil.getAuthorization("POST", convertProperties.getConvert(), contentMd5, headerDate, convertProperties.getAppid(), convertProperties.getAppsecret()); //签名

        //header参数
        Map<String, String> headers = new LinkedHashMap<>();
        headers.put(HttpHeaders.CONTENT_TYPE, Common.CONTENTTYPE);
        headers.put(HttpHeaders.DATE, headerDate);
        headers.put(HttpHeaders.CONTENT_MD5, contentMd5);//文档上是 "Content-Md5"
        headers.put(HttpHeaders.AUTHORIZATION, authorization);

        // 请求
        String result = HttpUtil.post(convertProperties.getConvert(), headers, JSON.toJSONString(param));
        if (!StringUtils.isEmpty(result)) {
            JSONObject dataJson = JSON.parseObject(result);
            String code = dataJson.get("Code").toString();
            if (code.equals("OK")) {
                //成功，做其它业务处理
            } else {
                String errorMsg = "文件格式转换失败";
                if (dataJson.get("Message") != null) {
                    String message = dataJson.get("Message").toString();
                    errorMsg = errorMsg + message;
                }
                //失败
            }
        }
    }


    /**
     * 文件转换查询
     *
     * @param taskId 任务id，由convertFil接口生成
     */
    public Object getConvertQueryRes(String taskId) {
        String headerDate = Common.getGMTDate();
        String downLoadUrl = "";
        try {
            //请求参数
            String contentMd5 = Common.getMD5(null); //请求内容数据的MD5值，用null作入参
            String url = convertProperties.getQuery() + "?TaskId=" + taskId + "&AppId=" + convertProperties.getAppid();
            String authorization = SignatureUtil.getAuthorization("GET", url, contentMd5, headerDate, convertProperties.getAppid(), convertProperties.getAppsecret()); //签名

            //header参数
            Map<String, String> headers = new LinkedHashMap<>();
            headers.put(HttpHeaders.CONTENT_TYPE, Common.CONTENTTYPE);
            headers.put(HttpHeaders.DATE, headerDate);
            headers.put(HttpHeaders.CONTENT_MD5, contentMd5);//文档上是 "Content-Md5"
            headers.put(HttpHeaders.AUTHORIZATION, authorization);

            //开始调用
            String result = HttpUtil.get(url, headers);
            if (!StringUtils.isEmpty(result)) {
                JSONObject dataJson = JSON.parseObject(result);
                String code = dataJson.get("Code").toString();
                if (code.equals("OK")) {
                    if (dataJson.get("Urls") != null) { //实际上返回这个参数
                        downLoadUrl = (dataJson.get("Urls")).toString();
                        // 源["xxx"]转换
                        JSONArray jsonArray = JSONArray.parseArray(downLoadUrl);
                        downLoadUrl = jsonArray.get(0).toString();
                    } else if (dataJson.get("Url") != null) {//文档是返回这个参数
                        downLoadUrl = dataJson.get("Url").toString();
                    }
                    //成功
                } else {
                    String errorMsg = "文件格式转换失败";
                    if (dataJson.get("Message") != null) {
                        String message = dataJson.get("Message").toString();
                        errorMsg = errorMsg + message;
                    }
                    //失败
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("recordWPSConvertResult处理出错，错误={}", e.getMessage(), e);
        }
        return downLoadUrl;
    }


    HttpServletRequest request;

    /**
     * 保存文件
     *
     * @param file     文件
     * @param w_userid 用户id
     */
    @Override
    public Map<String, Object> fileSave(MultipartFile multipartFile, String w_userid, Map<String, Object> params) {
        Date date = new Date();
        //上传
        String uploadType = Convert.toStr(params.get("_w_uploadType"));

        HashMap<String, Object> map = new HashMap<>();
        if (!Convert.toStr(params.get("_w_bucket")).contains("copy")){
            Example example = new Example(DfsFile.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("puuid", Convert.toStr(params.get("_w_fileId")));
            List<DfsFile> list = dfsFileService.selectByExample(example);
            DfsFile dfsFile = list.get(0);
            String filepath = dfsFile.getUrl();
            String fileName = dfsFile.getFileName();

            int fileSize = FileUtil.getFileSize(filepath);
            dfsFile.setFileSize(String.valueOf(fileSize) + "K");
            dfsFile.setModifier(Convert.toStr(params.get("_w_userName")));
            dfsFile.setModifierId(Convert.toStr(params.get("_w_userId")));
            dfsFile.setModifyTime(DateUtil.date(System.currentTimeMillis()));

            Example example1 = new Example(DfsFile.class);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("puuid", Convert.toStr(params.get("_w_fileId")));
            dfsFileService.updateByExample(dfsFile, example1);
            try {
                minioController.updateFile(multipartFile, Convert.toStr(params.get("_w_bucket")), fileName);
                FileEntity file = new FileEntity();
                file.setId(w_userid);
                file.setName(fileName);
                file.setVersion(1);
                file.setSize(fileSize);
                file.setDownloadUrl(filepath);
                map.put("file", file);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }else {
            String url = dfsFileService.selectCopyFileUrlByBusinessUuid(Convert.toStr(params.get("_w_fileId")));
            Object bucketAndFileName = minioController.getBucketAndFileName(url);
            String fileName = Convert.toStr(((HashMap) bucketAndFileName).get("fileName"));
            int fileSize = FileUtil.getFileSize(url);

            try {
                minioController.updateFile(multipartFile, Convert.toStr(params.get("_w_bucket")), fileName);
                FileEntity file = new FileEntity();
                file.setId(w_userid);
                file.setName(fileName);
                file.setVersion(1);
                file.setSize(fileSize);
                file.setDownloadUrl(url);
                map.put("file", file);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return map;

    }

    /**
     * 查询文件版本
     *
     * @param version 版本号
     */
    @Override
    public Map<String, Object> fileVersion(Integer version) {
        FileDTO fileInfo = new FileDTO();
        //String fileId = Context.getFileId();
        String fileId = "1";
        //FileVersionEntity fileVersion = fileVersionService.getRepository().findByFileIdAndVersion(fileId, version);
        FileVersionEntity fileVersion = new FileVersionEntity();
        if (fileVersion != null) {
            BeanUtils.copyProperties(fileVersion, fileInfo);
            fileInfo.setId(fileVersion.getFileId());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("file", fileInfo);
        return map;
    }

    @Override
    public void fileRename(String name, String w_userid, Map<String, Object> params) {
        String uploadType = params.get("_w_uploadType").toString();

        if (uploadType.equalsIgnoreCase(UploadFileLocation.OSS)) {
            logger.info("OSS===", UploadFileLocation.OSS);
        } else if (uploadType.equalsIgnoreCase(UploadFileLocation.FDFS)) {
            logger.info("FDFS===", UploadFileLocation.FDFS);
        } else if (uploadType.equalsIgnoreCase(UploadFileLocation.MINIO)) {
            logger.info("MINIO===", UploadFileLocation.MINIO);

            if (!Convert.toStr(params.get("_w_bucket")).contains("copy")){
                Example example = new Example(DfsFile.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("puuid", Convert.toStr(params.get("_w_fileId")));
                List<DfsFile> list = dfsFileService.selectByExample(example);
                DfsFile dfsFile = list.get(0);
                dfsFile.setModifier(Convert.toStr(params.get("_w_userName")));
                dfsFile.setModifierId(Convert.toStr(params.get("_w_userid")));
                dfsFile.setModifyTime(DateUtil.date(System.currentTimeMillis()));
                String oldUrl = dfsFile.getUrl();
                String oldFileName = dfsFile.getFileName();
                String newUrl = oldUrl.replace(oldFileName, name);
                dfsFile.setFileName(name);
                dfsFile.setUrl(newUrl);

                Example example1 = new Example(DfsFile.class);
                Example.Criteria criteria1 = example1.createCriteria();
                criteria1.andEqualTo("puuid", Convert.toStr(params.get("_w_fileId")));
                Integer integer = dfsFileService.updateByExample(dfsFile, example1);

                minioController.updateFileName(Convert.toStr(params.get("_w_bucket")), oldFileName, name);

                if (integer > 0){
                    logger.info("更新表名成功，更新前表名:{}，更新后表名:{}", oldFileName, name);
                }
            }else {
                String oldUrl = dfsFileService.selectCopyFileUrlByBusinessUuid(Convert.toStr(params.get("_w_fileId")));
                String modifier = Convert.toStr(params.get("_w_userName"));
                String modifierId = Convert.toStr(params.get("_w_userid"));
                DateTime modifyTime = DateUtil.date(System.currentTimeMillis());
                Object bucketAndFileName = minioController.getBucketAndFileName(oldUrl);
                String oldFileName = Convert.toStr(((HashMap) bucketAndFileName).get("fileName"));
                String newUrl = oldUrl.replace(oldFileName, name);
                Integer integer = dfsFileService.updateCopyFileUrlByBusinessUuid(Convert.toStr(params.get("_w_fileId")), newUrl, modifier, modifierId, modifyTime);
                minioController.updateFileName(Convert.toStr(params.get("_w_bucket")), oldFileName, name);
                if (integer > 0){
                    logger.info("更新表名成功，更新前表名:{}，更新后表名:{}", oldFileName, name);
                }
            }

        }
    }

    /**
     * 查询文件历史记录
     */
    @Override
    public Map<String, Object> fileHistory(FileReqDTO req) {
        List<FileHisDTO> result = new ArrayList<>(1);
        if (req.getId() != null) {
            // 目前先实现获取所有的历史记录
            //List<FileVersionEntity> versionList =
            //        fileVersionService.getRepository().findByFileIdOrderByVersionDesc(req.getId());
            List<FileVersionEntity> versionList = new ArrayList<>();
            if (versionList != null && versionList.size() > 0) {
                Set<String> userIdSet = new HashSet<>();
                for (FileVersionEntity fileVersion : versionList) {
                    userIdSet.add(fileVersion.getModifier());
                    userIdSet.add(fileVersion.getCreator());
                }
                List<String> userIdList = new ArrayList<>(userIdSet);
                // 获取所有关联的人
                //List<UserEntity> userList = userService.getRepository().findByIdIn(userIdList);
                List<UserEntity> userList = new ArrayList<>();
                if (userList != null && userList.size() > 0) {
                    for (FileVersionEntity fileVersion : versionList) {
                        FileHisDTO fileHis = new FileHisDTO();
                        BeanUtils.copyProperties(fileVersion, fileHis);
                        fileHis.setId(fileVersion.getFileId());
                        UserDTO creator = new UserDTO();
                        UserDTO modifier = new UserDTO();
                        for (UserEntity user : userList) {
                            if (user.getId().equals(fileVersion.getCreator())) {
                                BeanUtils.copyProperties(user, creator);
                            }
                            if (user.getId().equals(fileVersion.getModifier())) {
                                BeanUtils.copyProperties(user, modifier);
                            }
                        }
                        fileHis.setModifier(modifier);
                        fileHis.setCreator(creator);
                        result.add(fileHis);
                    }
                }
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("histories", result);
        return map;
    }


    /**
     * 新建文件
     *
     * @param file   文件
     * @param userId 用户id
     */
    @Override
    public Map<String, Object> fileNew(MultipartFile file, String userId, Map<String, Object> params) {
        try {
            Object resultMap = minioController.uploadMultipartFileWps(file, file.getName(), params);
            Map<String, Object> map = new HashMap<>();
            map.put("redirect_url", this.getViewUrl(Convert.toStr(params.get("_w_puuid")), userId, false, Convert.toStr(params.get("_w_bucket"))).getWpsUrl());
            map.put("user_id", params.get("_w_userid"));
            return map;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void convertCallBack(HttpServletRequest request) {
        try {
            BufferedReader buf = request.getReader();
            String str;
            StringBuilder data = new StringBuilder();
            while ((str = buf.readLine()) != null) {
                data.append(str);
            }
            logger.info("文件转换callBask取得data={}", data);
            if (data.length() > 0) {
                JSONObject dataJson = JSON.parseObject(data.toString());
                if (dataJson.get("Code") != null) {
                    String code = (String) dataJson.get("Code");
                    String taskId = (String) dataJson.get("TaskId");
                    Object url = getConvertQueryRes(taskId);
                    if (!StringUtils.isEmpty(url) && code.equalsIgnoreCase(HttpStatus.OK.getReasonPhrase())) {
                        //
                        System.out.println(url);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object fileOnline(JSONObject toJSON, Map<String, Object> params) {
        ArrayList<String> list = (ArrayList<String>) toJSON.get("ids");
//        for (int i = 0; i < list.size(); i++) {
//            Map<String, Object> user = userClient.getUserByUserNameId(list.get(i));
//            sendSimpleMail(user, messageClient, params);
//            sendSms(user, messageClient, params);
//            save(user, messageClient, params);
//        }
        return JsonUtils.messageJson(200, "操作提示", "通知成功");
    }


    @Autowired
    private MessageClient messageClient;

    @Autowired
    private MdataClient userClient;

    //发送邮件
    private void sendSimpleMail(Map<String, Object> user, MessageClient messageClient, Map<String, Object> params) {
        //获取用户详情数据
        Map<String, Object> map = new HashMap<>();
        map.put("toMail", Convert.toStr(user.get("email")));
        map.put("subject", "文件修改通知");
        map.put("content", Convert.toStr(user.get("userName")) + "(" + Convert.toStr(user.get("userNameId")) + ")" + "正在处理" + Convert.toStr(params.get("_w_fname")) + "+文件");
        Object object = messageClient.sendSimpleMail(map);
        logger.info("发送邮件{}", object);
    }

    //发送短信
    private void sendSms(Map<String, Object> user, MessageClient messageClient, Map<String, Object> params) {
        String message = "{businessStatus:'" + Convert.toStr(user.get("userName")) + "(" + Convert.toStr(user.get("userNameId")) + ")" + "正在处理" + Convert.toStr(params.get("_w_fname")) + "文件'}";
        Object object = messageClient.sendSms(user.get("cellphone").toString(), "湖南佐佑时代科技有限公司", "SMS_162220712",
                message, user.get("userNameId").toString());
        logger.info("发送短信{}", object);
    }

    //站内信
    private void save(Map<String, Object> user, MessageClient messageClient, Map<String, Object> params) {
        Map<String, Object> map = new HashMap<>();
        map.put("title", "文件修改通知");
        map.put("type", "文件修改");
        map.put("description", "文件修改");
        map.put("receiverId", user.get("userNameId").toString());
        map.put("url", 1);
        map.put("content", user.get("userName").toString() + "(" + user.get("userNameId").toString() + ")" + "正在处理+" + params.get("_w_fname").toString() + "+文件");
        Object object = messageClient.save(map);
        logger.info("发站内信{}", object);

    }

}
